﻿using Application.Common.Interfaces;
using Application.Features.Roles.DTOs;
using AutoMapper;
using AutoMapper.QueryableExtensions;
using Common.Attributes;
using MediatR;
using Microsoft.EntityFrameworkCore;
using System.ComponentModel;

namespace Application.Features.Roles.Queries.GetAll;

/// <summary>
/// 查询全部角色
/// </summary>
[Description("全部查询")]
[GroupDescription(("角色管理"))]
public class GetAllRolesQuery : IRequest<IEnumerable<RoleOutput>>
{
    public long? UserId { get; set; }
}

public class GetAllRolesQueryHandler :
    IRequestHandler<GetAllRolesQuery, IEnumerable<RoleOutput>>
{
    private readonly IApplicationDbContext _context;
    private readonly IMapper _mapper;

    public GetAllRolesQueryHandler(
        IApplicationDbContext context,
        IMapper mapper
    )
    {
        _context = context;
        _mapper = mapper;
    }

    public async Task<IEnumerable<RoleOutput>> Handle(GetAllRolesQuery request, CancellationToken cancellationToken)
    {
        var query = _context.Roles
            .Include(x=>x.UserRoles)
            .AsQueryable();

        //query = query.Where(x => x.IsActive);
        if (request.UserId.HasValue)
        {
            query = query.Where(x => x.UserRoles.Any(ur => ur.UserId == request.UserId.Value));
        }

        return await query.ProjectTo<RoleOutput>(_mapper.ConfigurationProvider).ToListAsync();
    }
}